package com.gzw.shop.activity;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.gzw.shop.App;
import com.gzw.shop.Contans;
import com.gzw.shop.R;
import com.gzw.shop.bean.ShoppingCart;
import com.gzw.shop.bean.Wares;
import com.gzw.shop.http.OkHttpHelper;
import com.gzw.shop.http.SpotsCallBack;
import com.gzw.shop.msg.BaseRespMsg;
import com.gzw.shop.utils.CartProvider;
import com.gzw.shop.utils.ToastUtils;
import com.gzw.shop.widget.GToolbar;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import dmax.dialog.SpotsDialog;
import okhttp3.Response;

public class WareDetailActivity extends BaseActivity {

    private GToolbar mGToolbar;
    private WebView mWebView;
    private WebJSInterface webjs;
    private Wares mwares;
    private CartProvider mProvider;
    private SpotsDialog mDialog;

    private Context context;

    private OkHttpHelper helper = OkHttpHelper.getInstance();

    @Override
    public int getLayoutId() {
        return R.layout.activity_ware_detail;
    }

    @Override
    public void initView() {

        context = this;

        Serializable serializable = getIntent().getSerializableExtra(Contans.WARES);
        if (serializable == null) {
            this.finish();
        }
        mwares = (Wares) serializable;

        mProvider = new CartProvider(this);

        mDialog = new SpotsDialog(this, "loading...");
        mDialog.show();

        mGToolbar = (GToolbar) findViewById(R.id.toolbar);
        mWebView = (WebView) findViewById(R.id.webview);
        mGToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mGToolbar.setRightBtnText("分享");
        mGToolbar.setRightBtnOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare();
            }
        });


        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBlockNetworkImage(false);//加载图片，设置为true不能加载图片
        settings.setAppCacheEnabled(true);//允许有缓存

        mWebView.loadUrl(Contans.API.WARES_CAMPAIN_DETAIL);

        webjs = new WebJSInterface(this);

        //设置android与JavaScript交互  appInterface为js调用android的类名字
        mWebView.addJavascriptInterface(webjs, "appInterface");
        mWebView.setWebViewClient(new WebClient());
    }

    @Override
    public void initData() {

    }

    //分享功能
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle("分享");
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl("http://www.baidu.com");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(mwares.getName());
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(mwares.getImgUrl());
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://www.baidu.com");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(mwares.getName());
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("商城");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://www.baidu.com");
        // 启动分享GUI
        oks.show(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(this);
    }

    class WebJSInterface {

        private Context context;

        public WebJSInterface(Context context) {
            this.context = context;
        }

        //android与JS交互
        @JavascriptInterface
        public void showDetail() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:showDetail(" + mwares.getId() + ")");
                }
            });
        }

        //JS与android交互  收藏
        @JavascriptInterface
        public void addToCart(long id) {
            addFavorites(id);
        }

        //JS与android交互  加入购物车
        @JavascriptInterface
        public void buy(long id) {
            mProvider.put(mwares);
            Toast.makeText(context, "已添加到购物车", Toast.LENGTH_SHORT).show();
        }
    }

    private void addFavorites(long id) {


        long userId = App.getInstance().getUser().getId();

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("ware_id", mwares.getId());

        helper.post(Contans.API.FAVORITE_CREATE, params, new SpotsCallBack<BaseRespMsg>(this) {
            @Override
            public void onSuccess(Response response, BaseRespMsg result) {

                if (result.getStatus() == 1) {
                    ToastUtils.show(context, "收藏成功");
                } else {
                    ToastUtils.show(context, result.getMessage());

                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });


    }

    class WebClient extends WebViewClient {

        //页面加载完触发
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
                //加载完页面之后再调用js
                webjs.showDetail();
            }
        }
    }
}
